﻿using CommonLib.Attr;
using CommonLib.Base;
using CommonLib.CodeEntity;
using CommonLib.Util;
using System.Text.RegularExpressions;

namespace Oracle.Lexer;

[Order(0)]
public class TypeLexer : BaseLexer
{
    public override bool Check()
        => Txt.Replace("%TYPE", "").Contains(" TYPE ");

    protected override BaseCodeEntity Run()
    {
        var entity = new TypeCodeEntity();
        var txt = Real;
        entity.EndComment = Comment;
        var name = Regex.Match(txt, "TYPE(.*?)[A|I]S").Result("$1");
        entity.Name = name;
        if(txt.Contains("OBJECT ") || txt.Contains("OBJECT("))
        {
            entity.Type = "OBJECT";
            var cols = Regex.Match(txt, "OBJECT\\s*\\((.*)\\)").Result("$1");
            ListParams(cols,entity.Objects);
        }
        else if(txt.Contains("RECORD ") || txt.Contains("RECORD("))
        {
            entity.Type = "RECORD";
            var cols = Regex.Match(txt, "RECORD\\s*\\((.*)\\)").Result("$1");
            ListParams(cols, entity.Objects);
        }
        else if (txt.Contains("TABLE "))
        {
            entity.Type = "TABLE";
            var end = Regex.Match(txt, " OF(.*)").Result("$1");
            if (end.Contains("INDEX BY"))
            {
                var idx = end[end.IndexOf("INDEX ")..].Trim();
                entity.IndexBy = idx;
                end = end.Replace(idx, "").Trim();
            }
            entity.OfType = OracleHelp.RealType(end);
        }
        else if(txt.Contains("VARRAY ") || txt.Contains("VARRAY("))
        {
            entity.Type = Regex.Match(txt, "VARRAY.*?\\)").Value;
            var end = Regex.Match(txt," OF(.*)").Result("$1");
            if(end.Contains("INDEX BY"))
            {
                var idx = end[end.IndexOf("INDEX ")..].Trim();
                entity.IndexBy =idx;
                end = end.Replace(idx,"").Trim();
            }
            entity.OfType = OracleHelp.RealType(end);
        }
        else if(txt.Contains("TYPE BODY"))
        {
            entity.Type = "TYPE BODY";
            var end = txt[txt.IndexOf("MEMEBER ")..].Trim();
            entity.Objects.Add(SqlFactory.Create(end).Execute());
        }
        return entity;
    }
}
